package com.lagou.order.service.impl;

import com.lagou.order.domain.Order;
import com.lagou.order.mapper.OrderMapper;
import com.lagou.order.service.OrderService;
import org.springframework.amqp.core.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AmqpTemplate template;

    @Override
    public Long takeOrder(Order order) {
        orderMapper.insert(order);
        Long id = order.getId();

        final MessageProperties messageProperties = MessagePropertiesBuilder.newInstance()
                // 设置消息的过期时间
                .setHeader("x-delay", 30 * 1000)
                .setContentEncoding("utf-8")
                .build();

        final Message message = MessageBuilder
                .withBody(id.toString().getBytes())
                .andProperties(messageProperties)
                .build();

        template.send("ex.delayed", "key.delayed", message);
        //将消息放到延时队列,
        return  id;
    }

    @Transactional
    @Override
    public Integer payOrder(Long orderId) {
        //首先查询订单
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Integer status = order.getStatus();
        if(status == 1){
            order.setStatus(2);
            orderMapper.updateByPrimaryKey(order);
            //付款成功
            return  1;
        }
        //付款失败
        return 0;
    }
}
